<template>
  <div class="flex bg-gray-50 text-dark">
    <!-- 右侧内容 B列 - 添加滚动容器 -->
    <div class="ml-[2.5%] mr-[2.5%] h-full flex-1 overflow-hidden">
      <!-- 内容滚动容器 -->
      <div class="h-full overflow-y-hidden pr-2" style="scrollbar-width: thin">
        <div class="pb-2">
          <!-- 顶部 Brow1：养殖池子图示区域 -->

          <div
            class="h-[45vh] bg-white rounded-xl shadow-sm p-4 mt-1 overflow-hidden flex flex-col"
          >
            <div class="flex justify-between items-center mb-4">
              <h2 class="text-lg font-semibold flex items-center">
                <i class="fa fa-th-large text-primary mr-2"></i>
                养殖池子监控
              </h2>
              <div class="flex items-center space-x-3">
                <div class="flex items-center text-sm">
                  <span class="mr-2 h-3 w-3 rounded-full bg-green"></span>
                  <span>正常</span>
                </div>
                <div class="flex items-center text-sm">
                  <span class="mr-2 h-3 w-3 rounded-full bg-orange"></span>
                  <span>预警</span>
                </div>
                <div class="flex items-center text-sm">
                  <span class="w-3 h-3 rounded-full bg-red mr-2"></span>

                  <span>告警</span>
                </div>
                <div class="flex items-center text-sm">
                  <span class="mr-2 h-3 w-3 rounded-full"></span>
                </div>
              </div>
            </div>

            <!-- 4×9 圆点阵列 - 添加水平滚动支持 -->
            <div class="flex-1 overflow-hidden">
              <div class="h-full overflow-x-auto">
                <div
                  id="tank-grid"
                  class="h-full w-full grid grid-cols-9 grid-rows-4 gap-2 p-2"
                >
                  <div
                    v-for="tank in tanks"
                    :key="tank.id"
                    :class="[
                      'tank-dot',
                      `tank-dot-${tank.status}`,
                      'scale-hover',
                      { 'tank-selected': selectedTankId === tank.id },
                    ]"
                    title="`养殖池 ${tank.id} - 第${tankProgress[tank.id]?.actualProgress || 45}天`"
                    @click="selectTank(tank.id)"
                    class="w-18 h-18 min-w-18 min-h-18"
                  >
                    <span
                      class="text-3xl font-medium absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2"
                      :style="{ color: getStatusColor(tank.status) }"
                    >
                      {{ tank.id }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 中间 Brow2：数据切换导航 → 拖动进度条 -->

          <div class="h-[15vh] flex items-center justify-center my-1">
            <div class="w-full relative">
              <div class="mt-4 text-center" style="margin-bottom: 10px">
                <span class="text-lg font-semibold text-primary">
                  {{
                    selectedTankId
                      ? `池子 ${selectedTankId} 当前进度：第${sliderValue}天`
                      : "请选择一个养殖池"
                  }}
                  <span
                    v-if="showRestoreFeedback"
                    class="restore-feedback text-green-500 ml-2"
                  >
                    <i class="fa fa-check"></i> 已恢复
                  </span>
                </span>
              </div>
              <div class="flex items-center gap-6">
                <span
                  class="w-16 text-right text-base text-gray-600 font-medium"
                  >{{ days[0].label }}</span
                >
                <div class="relative flex-1">
                  <input
                    type="range"
                    min="1"
                    :max="currentSliderMax"
                    step="1"
                    v-model.number="sliderValue"
                    @input="onSliderInput"
                    class="slider w-full"
                    :style="{
                      background: sliderBackground,
                    }"
                    :disabled="!selectedTankId"
                  />
                  <div
                    class="absolute left-0 right-0 top-8 flex justify-between text-xs text-gray-500"
                  >
                    <span v-for="day in getDynamicDays()" :key="day.id">{{
                      day.label
                    }}</span>
                  </div>
                </div>
                <span class="w-16 text-base text-gray-600 font-medium">{{
                  selectedTankId ? `第100天` : days[days.length - 1].label
                }}</span>
              </div>
              <!-- 恢复按钮 -->
              <button
                @click="resetToProgress"
                class="bg-primary hover:bg-primary/80 absolute right-0 top-0 flex items-center gap-1 rounded-lg px-3 py-1 text-sm text-blue-500 transition-colors"
                :title="
                  selectedTankId
                    ? `恢复到池子 ${selectedTankId} 的实际养殖进度`
                    : '恢复进度'
                "
                :disabled="!selectedTankId"
                :class="{ 'restore-button-animate': showRestoreFeedback }"
              >
                <i class="fa fa-refresh"></i>
                恢复
              </button>
            </div>
          </div>

          <!-- 底部 Brow3：内容显示区域 - 改为上下布局 -->
          <div class="h-[50vh] flex flex-col gap-2 mb-1">
            <!-- 上部分：监控区域和饲料使用情况 -->
            <div class="flex flex-1 gap-2">
              <!-- 左侧：监控区域（横向合并） -->
              <div
                class="w-1/2 overflow-hidden rounded-xl bg-white p-3 shadow-sm"
              >
                <h3 class="mb-2 flex items-center text-sm font-medium">
                  <i class="fa fa-video-camera text-primary mr-2"></i>
                  监控区域
                </h3>
                <div class="h-[calc(100%-20px)] w-full flex gap-2">
                  <!-- 监控区域1 -->
                  <div
                    class="relative flex-1 overflow-hidden rounded-lg bg-gray-100"
                  >
                    <img
                      src="@/assets/images/chizi1.png"
                      alt="养殖池监控画面"
                      class="h-full w-full object-cover"
                    />
                    <div
                      class="bg-primary/80 absolute right-2 top-2 flex items-center rounded-full px-2 py-1 text-xs text-white"
                    >
                      <span
                        class="mr-1 h-2 w-2 animate-pulse rounded-full bg-white"
                      ></span>
                      监控1
                    </div>
                  </div>

                  <!-- 监控区域2 -->
                  <div
                    class="relative flex-1 overflow-hidden rounded-lg bg-gray-100"
                  >
                    <img
                      src="@/assets/images/chizi2.png"
                      alt="养殖池监控画面"
                      class="h-full w-full object-cover"
                    />
                    <div
                      class="bg-primary/80 absolute right-2 top-2 flex items-center rounded-full px-2 py-1 text-xs text-white"
                    >
                      <span
                        class="mr-1 h-2 w-2 animate-pulse rounded-full bg-white"
                      ></span>
                      监控2
                    </div>
                  </div>
                </div>
              </div>

              <!-- 右侧：饲料使用情况 -->
              <div
                class="w-1/2 overflow-y-auto rounded-xl bg-white p-3 shadow-sm"
              >
                <h3 class="mb-2 flex items-center text-sm font-medium">
                  <i class="fa fa-cutlery text-primary mr-2"></i>
                  饲料使用情况
                </h3>
                <div class="space-y-2">
                  <div
                    class="flex items-center justify-between border-b border-gray-100 p-1"
                  >
                    <span class="text-sm text-gray-700">批次编号</span>
                    <span class="text-sm font-medium">{{
                      selectedTankId ? feedInfo.batchNumber : "--"
                    }}</span>
                  </div>
                  <div
                    class="flex items-center justify-between border-b border-gray-100 p-1"
                  >
                    <span class="text-sm text-gray-700">投喂量</span>
                    <span class="text-sm font-medium">{{
                      selectedTankId ? feedInfo.feedAmount : "--"
                    }}</span>
                  </div>
                  <div
                    class="flex items-center justify-between border-b border-gray-100 p-1"
                  >
                    <span class="text-sm text-gray-700">投喂时间</span>
                    <span class="text-sm font-medium">{{
                      selectedTankId ? feedInfo.feedTime : "--"
                    }}</span>
                  </div>
                  <div
                    class="flex items-center justify-between border-b border-gray-100 p-1"
                  >
                    <span class="text-sm text-gray-700">投喂员</span>
                    <span class="text-sm font-medium">{{
                      selectedTankId ? feedInfo.feeder : "--"
                    }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 下部分：5个小K线图 -->
            <div
              class="flex-1 overflow-hidden rounded-xl bg-white p-3 shadow-sm"
            >
              <h3 class="mb-2 flex items-center text-sm font-medium">
                <i class="fa fa-line-chart text-primary mr-2"></i>
                水质参数监控 - 24小时变化
                <span v-if="isLoading" class="ml-2 text-sm text-gray-500">
                  <i class="fa fa-spinner fa-spin"></i> 加载中...
                </span>
                <span v-if="hasError" class="ml-2 text-sm text-red-500">
                  <i class="fa fa-exclamation-circle"></i> 数据加载失败
                </span>
              </h3>
              <div class="grid grid-cols-5 h-[calc(100%-30px)] w-full gap-2">
                <!-- 水温图表 -->
                <div class="chart-container">
                  <div class="chart-title">水温 (°C)</div>
                  <canvas ref="tempChart" class="water-quality-chart"></canvas>
                </div>

                <!-- PH值图表 -->
                <div class="chart-container">
                  <div class="chart-title">PH值</div>
                  <canvas ref="phChart" class="water-quality-chart"></canvas>
                </div>

                <!-- 盐度图表 -->
                <div class="chart-container">
                  <div class="chart-title">盐度 (%)</div>
                  <canvas
                    ref="salinityChart"
                    class="water-quality-chart"
                  ></canvas>
                </div>

                <!-- 水位图表 -->
                <div class="chart-container">
                  <div class="chart-title">水位 (m)</div>
                  <canvas
                    ref="waterLevelChart"
                    class="water-quality-chart"
                  ></canvas>
                </div>

                <!-- 溶解氧图表 -->
                <div class="chart-container">
                  <div class="chart-title">溶解氧 (mg/L)</div>
                  <canvas
                    ref="oxygenChart"
                    class="water-quality-chart"
                  ></canvas>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, reactive, computed, watch } from "vue";
import Chart from "chart.js/auto";
import axios from "axios";

// 图表实例变量
let tempChartInstance = null;
let phChartInstance = null;
let salinityChartInstance = null;
let waterLevelChartInstance = null;
let oxygenChartInstance = null;

export default {
  setup() {
    // 响应式数据
    const buildingOpen = reactive({
      "001": true,
      "002": false,
      "003": false,
    });

    const activeFloor = ref("001");
    const activeDay = ref("day45");
    const sliderValue = ref(45);
    const selectedTankId = ref(1);
    const showRestoreFeedback = ref(false);
    const restoreFeedbackTimer = ref(null);

    // 新增：数据加载状态
    const isLoading = ref(false);
    const hasError = ref(false);

    // 水质参数图表引用
    const tempChart = ref(null);
    const phChart = ref(null);
    const salinityChart = ref(null);
    const waterLevelChart = ref(null);
    const oxygenChart = ref(null);

    // 为每个池子存储进度数据：实际进度和当前显示进度
    const tankProgress = reactive({});

    // 池子最新进度限制（1和2池子的最新进度是30天）
    const getLatestProgress = (tankId) => {
      if (tankId === 1 || tankId === 2) {
        return 30; // 1和2池子最新进度30天
      }
      return 100; // 其他池子最新进度100天
    };

    // 当前进度条的最大值（总天数保持100天）
    const currentSliderMax = ref(100);

    // 获取当前池子的可拖动最大天数
    const getDraggableMax = (tankId) => {
      if (!tankId) return 100;
      return getLatestProgress(tankId);
    };

    // 根据当前池子动态生成日期标签（总天数保持100天）
    const getDynamicDays = () => {
      if (!selectedTankId.value) return days;

      // 总天数始终是100天
      const totalDays = 100;
      const step = Math.floor(totalDays / 5);

      return [
        { id: "day1", label: "第1天" },
        { id: `day${Math.floor(step)}`, label: `第${Math.floor(step)}天` },
        {
          id: `day${Math.floor(step * 2)}`,
          label: `第${Math.floor(step * 2)}天`,
        },
        {
          id: `day${Math.floor(step * 3)}`,
          label: `第${Math.floor(step * 3)}天`,
        },
        {
          id: `day${Math.floor(step * 4)}`,
          label: `第${Math.floor(step * 4)}天`,
        },
        { id: `day${totalDays}`, label: `第${totalDays}天` },
      ];
    };

    const fillPercent = computed(() => {
      if (!selectedTankId.value) return "0%";

      const currentValue = sliderValue.value;
      const ratio = (currentValue - 1) / (currentSliderMax.value - 1);
      return `${Math.max(0, Math.min(1, ratio)) * 100}%`;
    });

    // 生成动态进度条背景色
    const sliderBackground = computed(() => {
      if (!selectedTankId.value) return "";

      const latestProgress = getLatestProgress(selectedTankId.value); // 当前池子最新进度（如1、2号池30天）
      const currentValue = sliderValue.value; // 当前拖动的进度（≤ latestProgress）
      const totalDays = currentSliderMax.value; // 总进度100天

      // 计算3个关键节点的百分比（基于总进度100天）
      const currentRatio = ((currentValue - 1) / (totalDays - 1)) * 100; // 当前进度百分比
      const latestRatio = ((latestProgress - 1) / (totalDays - 1)) * 100; // 最新进度百分比（禁用区域起点）

      // 进度条背景：绿色（已选）→ 浅绿色（可选）→ 灰色（禁用）
      return `linear-gradient(
    90deg,
    #52c41a 0%,                /* 起点 */
    #52c41a ${currentRatio}%,   /* 当前进度前：绿色（已选区域） */
    #a7f3d0 ${currentRatio}%,   /* 当前进度~最新进度：浅绿色（可选区域，视觉区分） */
    #a7f3d0 ${latestRatio}%,    /* 最新进度前：结束浅绿色 */
    #9ca3af ${latestRatio}%,    /* 最新进度~100天：灰色（禁用区域） */
    #9ca3af 100%                /* 终点 */
  )`;
    });

    const progressPercent = computed(() => {
      if (!selectedTankId.value) return "0%";
      const currentProgress =
        tankProgress[selectedTankId.value]?.actualProgress || 45;
      const latestProgress = getLatestProgress(selectedTankId.value);
      const ratio = (currentProgress - 1) / (latestProgress - 1);
      return `${Math.max(0, Math.min(1, ratio)) * 100}%`;
    });

    // 水质参数图表引用
    const waterQualityChart = ref(null);

    // 水质参数范围定义
    const waterQualityRanges = {
      temperature: { min: 20, max: 29, unit: "°C" },
      ph: { min: 7.3, max: 8.8, unit: "" },
      salinity: { min: 10, max: 26, unit: "%" },
      waterLevel: { min: 0.7, max: 1.45, unit: "m" },
      oxygen: { min: 5.1, max: 8.5, unit: "mg/L" },
    };

    // 选中养殖池
    const selectTank = (tankId) => {
      // 如果点击的是已选中的池子，则取消选中
      if (selectedTankId.value === tankId) {
        selectedTankId.value = null;
        sliderValue.value = 45; // 重置为默认值
      } else {
        selectedTankId.value = tankId;

        // 如果该池子还没有进度数据，初始化进度
        if (!tankProgress[tankId]) {
          // 为不同池子设置不同的随机进度，但不超过最新进度限制
          const latestProgress = getLatestProgress(tankId);
          const actualProgress = Math.min(
            Math.floor(Math.random() * 50) + 30,
            latestProgress
          );
          tankProgress[tankId] = {
            actualProgress: actualProgress,
            displayProgress: actualProgress, // 初始时显示进度等于实际进度
          };
        }

        // 更新滑块值为当前选中池子的显示进度
        sliderValue.value = tankProgress[tankId].displayProgress;

        // 更新饲料信息（模拟不同池子的不同饲料信息）
        updateFeedInfo(tankId);

        // 更新水质参数图表（从API获取数据）
        fetchAndUpdateWaterQualityCharts(tankId, sliderValue.value);

        console.log(
          `选中养殖池 ${tankId}，实际进度：第${tankProgress[tankId].actualProgress}天，显示进度：第${tankProgress[tankId].displayProgress}天`
        );
      }

      // 隐藏恢复反馈
      showRestoreFeedback.value = false;
      if (restoreFeedbackTimer.value) {
        clearTimeout(restoreFeedbackTimer.value);
      }
    };

    // 调用接口获取饲料信息
    const fetchFeedInfo = async (pondId, days) => {
      try {
        const response = await axios.post(
          "http://8.148.149.77:8041/api/feeding/query",
          {
            pondId: pondId,
            days: days,
          }
        );

        if (response.data && response.data.length > 0) {
          const feedData = response.data[0];
          Object.assign(feedInfo, {
            batchNumber: feedData.batchNumber,
            feedAmount: `${feedData.feedingAmount}kg`,
            feedTime: feedData.feedingTime,
            feeder: feedData.feeder,
            remainingAmount: "300kg", // 接口没有剩余量，使用默认值
          });
        } else {
          // 如果没有数据，使用默认值
          Object.assign(feedInfo, {
            batchNumber: `${pondId
              .toString()
              .padStart(3, "0")}-ct${pondId}-${days}`,
            feedAmount: "100kg",
            feedTime: "08:30, 14:30",
            feeder: "默认投喂员",
            remainingAmount: "300kg",
          });
        }
      } catch (error) {
        console.error("获取饲料信息失败:", error);
        // 出错时使用默认数据
        Object.assign(feedInfo, {
          batchNumber: `${pondId
            .toString()
            .padStart(3, "0")}-ct${pondId}-${days}`,
          feedAmount: "100kg",
          feedTime: "08:30, 14:30",
          feeder: "默认投喂员",
          remainingAmount: "300kg",
        });
      }
    };

    // 更新饲料信息（调用接口）
    const updateFeedInfo = (tankId) => {
      // 获取当前进度条的天数
      const currentDays = sliderValue.value;
      // 调用接口获取饲料信息
      fetchFeedInfo(tankId, currentDays);
    };

    const tanks = ref([]);

    // 日期数据
    const days = [
      { id: "day1", label: "第1天" },
      { id: "day20", label: "第20天" },
      { id: "day40", label: "第40天" },
      { id: "day60", label: "第60天" },
      { id: "day80", label: "第80天" },
      { id: "day100", label: "第100天" },
    ];

    // 饲料信息
    const feedInfo = reactive({
      batchNumber: "001-ct1-24",
      feedAmount: "120kg",
      feedTime: "08:30, 14:30",
      feeder: "张三",
      remainingAmount: "350kg",
    });

    // 成长趋势图表引用
    const growthChart = ref(null);

    // 方法
    const toggleBuildingMenu = (buildingId) => {
      buildingOpen[buildingId] = !buildingOpen[buildingId];
    };

    const setActiveFloor = (floorId) => {
      activeFloor.value = floorId;
    };

    const setActiveDay = (dayId) => {
      activeDay.value = dayId;
      const dayNumber = parseInt(dayId.replace("day", ""));

      // 检查是否超过当前选中池子的最新进度限制
      if (selectedTankId.value) {
        const latestProgress = getLatestProgress(selectedTankId.value);
        if (dayNumber > latestProgress) {
          sliderValue.value = latestProgress;
          return;
        }
      }

      sliderValue.value = dayNumber;
    };

    const onSliderInput = () => {
      if (!selectedTankId.value) return;

      const latestProgress = getLatestProgress(selectedTankId.value);
      // 关键：强制进度条不超过“最新进度”，也不低于1
      sliderValue.value = Math.min(
        Math.max(1, sliderValue.value),
        latestProgress
      );
      const dayNumber = sliderValue.value;

      // 更新显示进度和图表、饲料信息
      if (tankProgress[selectedTankId.value]) {
        tankProgress[selectedTankId.value].displayProgress = dayNumber;
      }

      const dayId = `day${dayNumber}`;
      if (dayId !== activeDay.value) {
        activeDay.value = dayId;
        // 从API获取数据并更新图表
        fetchAndUpdateWaterQualityCharts(selectedTankId.value, dayNumber);
        if (selectedTankId.value) {
          fetchFeedInfo(selectedTankId.value, dayNumber);
        }
      }

      showRestoreFeedback.value = false;
      if (restoreFeedbackTimer.value) {
        clearTimeout(restoreFeedbackTimer.value);
      }
    };

    // 更新成长趋势图表
    const updateGrowthChart = (dayNumber) => {
      if (growthChartInstance) {
        const data = getGrowthData(dayNumber);
        growthChartInstance.data.labels = data.labels;
        growthChartInstance.data.datasets[0].data = data.bodyLength;
        growthChartInstance.data.datasets[1].data = data.survivalRate;
        growthChartInstance.update("active");
      }
    };

    const resetToProgress = () => {
      if (!selectedTankId.value || !tankProgress[selectedTankId.value]) return;

      fetchFeedInfo(selectedTankId.value, 30);

      // 获取当前选中池子的实际进度
      const actualProgress = tankProgress[selectedTankId.value].actualProgress;

      // 恢复到实际进度
      sliderValue.value = actualProgress;
      tankProgress[selectedTankId.value].displayProgress = actualProgress;
      activeDay.value = `day${actualProgress}`;

      // 从API获取数据并更新图表
      fetchAndUpdateWaterQualityCharts(selectedTankId.value, actualProgress);

      // 显示恢复反馈
      showRestoreFeedback.value = true;
      if (restoreFeedbackTimer.value) {
        clearTimeout(restoreFeedbackTimer.value);
      }
      restoreFeedbackTimer.value = setTimeout(() => {
        showRestoreFeedback.value = false;
      }, 2000);

      console.log(
        `池子 ${selectedTankId.value} 已恢复到实际进度：第${actualProgress}天`
      );
    };

    // 生成养殖池数据
    const generateTankGrid = () => {
      const statuses = ["normal", "normal", "normal", "warning", "alert"];
      const newTanks = [];

      for (let i = 1; i <= 36; i++) {
        // 随机选择状态，大部分为正常
        const randomIndex =
          Math.random() > 0.9
            ? Math.floor(Math.random() * 2) + 3 // 10%概率为warning或alert
            : 0; // 90%概率为normal

        newTanks.push({
          id: i,
          status: statuses[randomIndex],
        });

        // 为每个池子初始化进度数据
        if (!tankProgress[i]) {
          const latestProgress = getLatestProgress(i);
          const actualProgress = Math.min(
            Math.floor(Math.random() * 50) + 30,
            latestProgress
          );
          tankProgress[i] = {
            actualProgress: actualProgress,
            displayProgress: actualProgress,
          };
        }
      }

      tanks.value = newTanks;
    };

    // 刷新养殖池数据
    const refreshTankGrid = () => {
      generateTankGrid();
    };

    // 获取状态对应的颜色
    const getStatusColor = (status) => {
      switch (status) {
        case "normal":
          return "#52C41A";
        case "warning":
          return "#FAAD14";
        case "alert":
          return "#FF4D4F";
        default:
          return "#52C41A";
      }
    };

    // 新增：从API获取水质数据并更新图表
    const fetchAndUpdateWaterQualityCharts = async (tankId, dayNumber) => {
      // 根据天数计算日期
      const baseDate = new Date(2025, 7, 30); // 8月30日是基准最新日期
      const targetDate = new Date(baseDate);
      targetDate.setDate(30 - (getLatestProgress(tankId) - dayNumber));

      // 格式化日期为"YYYY-MM-DD"
      const year = targetDate.getFullYear();
      const month = String(targetDate.getMonth() + 1).padStart(2, "0");
      const day = String(targetDate.getDate()).padStart(2, "0");
      const dateStr = `${year}-${month}-${day}`;

      // 设置请求参数
      const params = {
        devId: tankId,
        start: `${dateStr} 00:00:00`,
        end: `${dateStr} 23:59:59`,
      };

      try {
        // 显示加载状态
        isLoading.value = true;
        hasError.value = false;

        // 发送请求
        const response = await axios.post(
          "http://8.148.149.77:8041/api/devdata/query",
          params
        );

        // 处理返回数据并更新图表
        if (response.data && Array.isArray(response.data)) {
          updateWaterQualityChartsWithApiData(response.data);
        } else {
          console.error("API返回数据格式不正确");
          hasError.value = true;
        }
      } catch (error) {
        console.error("获取水质数据失败:", error);
        hasError.value = true;
      } finally {
        // 隐藏加载状态
        isLoading.value = false;
      }
    };

    // 新增：使用API数据更新图表
    const updateWaterQualityChartsWithApiData = (apiData) => {
      // 准备图表数据
      const chartData = {
        labels: [],
        temperature: [],
        ph: [],
        salinity: [],
        waterLevel: [],
        oxygen: [],
      };

      // 处理API返回的数据
      apiData.forEach((item) => {
        // 格式化时间标签（只保留小时）
        const time = new Date(item.createdAt);
        const hour = time.getHours();
        chartData.labels.push(`${hour}:00`);

        // 提取各项指标
        chartData.temperature.push(item.waterTemp);
        chartData.ph.push(item.ph);
        chartData.salinity.push(item.salinity);
        chartData.waterLevel.push(item.waterLevel);
        chartData.oxygen.push(item.dissolvedOxygen);
      });

      // 更新各个图表
      if (tempChartInstance) {
        tempChartInstance.data.labels = chartData.labels;
        tempChartInstance.data.datasets[0].data = chartData.temperature;
        tempChartInstance.update("active");
      }

      if (phChartInstance) {
        phChartInstance.data.labels = chartData.labels;
        phChartInstance.data.datasets[0].data = chartData.ph;
        phChartInstance.update("active");
      }

      if (salinityChartInstance) {
        salinityChartInstance.data.labels = chartData.labels;
        salinityChartInstance.data.datasets[0].data = chartData.salinity;
        salinityChartInstance.update("active");
      }

      if (waterLevelChartInstance) {
        waterLevelChartInstance.data.labels = chartData.labels;
        waterLevelChartInstance.data.datasets[0].data = chartData.waterLevel;
        waterLevelChartInstance.update("active");
      }

      if (oxygenChartInstance) {
        oxygenChartInstance.data.labels = chartData.labels;
        oxygenChartInstance.data.datasets[0].data = chartData.oxygen;
        oxygenChartInstance.update("active");
      }
    };

    // 初始化单个水质参数图表
    const initWaterQualityChart = (
      chartRef,
      chartInstance,
      paramName,
      title,
      color
    ) => {
      if (chartRef.value) {
        // 销毁现有图表实例（如果存在）
        if (chartInstance) {
          chartInstance.destroy();
        }

        const range = waterQualityRanges[paramName];

        return new Chart(chartRef.value, {
          type: "line",
          data: {
            labels: [],
            datasets: [
              {
                label: title,
                data: [],
                borderColor: color,
                backgroundColor: "transparent", // 修改为透明背景
                borderWidth: 2,
                fill: false, // 取消填充
                tension: 0.4, // 保持曲线平滑
                pointRadius: 0, // 移除圆点
                pointHoverRadius: 3, // 悬停时显示圆点
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
              legend: {
                display: false,
              },
              tooltip: {
                mode: "index",
                intersect: false,
                callbacks: {
                  label: function (context) {
                    return `${title}: ${context.raw}${range.unit}`;
                  },
                },
              },
            },
            scales: {
              x: {
                grid: {
                  display: false,
                  color: "rgba(0, 0, 0, 0.1)", // 添加浅色网格线
                },
                ticks: {
                  maxRotation: 0,
                  autoSkip: true,
                  maxTicksLimit: 6,
                  color: "#6B7280", // 设置文字颜色
                },
              },
              y: {
                min: range.min - (range.max - range.min) * 0.1,
                max: range.max + (range.max - range.min) * 0.1,
                grid: {
                  color: "rgba(0, 0, 0, 0.1)", // 浅色网格线
                },
                ticks: {
                  color: "#6B7280", // 设置文字颜色
                },
              },
            },
          },
        });
      }
      return null;
    };

    // 初始化所有水质参数图表
    const initWaterQualityCharts = () => {
      tempChartInstance = initWaterQualityChart(
        tempChart,
        tempChartInstance,
        "temperature",
        "水温",
        "rgba(255, 99, 132, 1)"
      );
      phChartInstance = initWaterQualityChart(
        phChart,
        phChartInstance,
        "ph",
        "PH值",
        "rgba(54, 162, 235, 1)"
      );
      salinityChartInstance = initWaterQualityChart(
        salinityChart,
        salinityChartInstance,
        "salinity",
        "盐度",
        "rgba(75, 192, 192, 1)"
      );
      waterLevelChartInstance = initWaterQualityChart(
        waterLevelChart,
        waterLevelChartInstance,
        "waterLevel",
        "水位",
        "rgba(255, 159, 64, 1)"
      );
      oxygenChartInstance = initWaterQualityChart(
        oxygenChart,
        oxygenChartInstance,
        "oxygen",
        "溶解氧",
        "rgba(153, 102, 255, 1)"
      );
    };

    // 移除原有的静态数据生成函数，改用API数据

    // 更新水质参数图表
    const updateWaterQualityChart = (dayNumber) => {
      if (waterQualityChartInstance) {
        // 现在这个方法会通过API获取数据，所以这里留空
        waterQualityChartInstance.update("active");
      }
    };

    // 响应窗口大小变化，调整圆点大小
    const handleResize = () => {
      generateTankGrid();
    };

    // 生命周期钩子
    onMounted(() => {
      // 初始化养殖池数据
      generateTankGrid();

      resetToProgress();

      // 初始化水质参数图表
      initWaterQualityCharts();

      // 如果有选中的池子，获取数据
      if (selectedTankId.value) {
        fetchAndUpdateWaterQualityCharts(
          selectedTankId.value,
          sliderValue.value
        );
      }

      // 添加窗口大小变化监听
      window.addEventListener("resize", handleResize);

      // 组件卸载时移除监听
      return () => {
        window.removeEventListener("resize", handleResize);
        if (restoreFeedbackTimer.value) {
          clearTimeout(restoreFeedbackTimer.value);
        }
        // 销毁所有图表实例
        [
          tempChartInstance,
          phChartInstance,
          salinityChartInstance,
          waterLevelChartInstance,
          oxygenChartInstance,
        ].forEach((instance) => instance && instance.destroy());
      };
    });

    return {
      buildingOpen,
      activeFloor,
      activeDay,
      sliderValue,
      fillPercent,
      progressPercent,
      tanks,
      days,
      feedInfo,
      waterQualityChart,
      selectedTankId,
      showRestoreFeedback,
      tempChart,
      phChart,
      salinityChart,
      waterLevelChart,
      oxygenChart,
      currentSliderMax,
      toggleBuildingMenu,
      setActiveFloor,
      setActiveDay,
      onSliderInput,
      resetToProgress,
      refreshTankGrid,
      selectTank,
      getStatusColor,
      getDynamicDays,
      getLatestProgress,
      sliderBackground,
      isLoading,
      hasError,
    };
  },
};
</script>

<style scoped>
/* 基础样式 */
html,
body {
  padding: 0;
  margin: 0;
}

/* 滚动条美化 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 动画效果 */
.fade-in {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.scale-hover {
  transition: transform 0.2s ease;
}

.scale-hover:hover {
  transform: scale(1.05);
}

/* 监控区域动画 */
.monitor-pulse {
  position: relative;
  overflow: hidden;
}

.monitor-pulse::after {
  content: "";
  position: absolute;
  top: 0;
  left: -100%;
  width: 50%;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255, 255, 255, 0.1),
    transparent
  );
  animation: shine 2s infinite;
}

@keyframes shine {
  100% {
    left: 100%;
  }
}

/* 导入自定义工具类的样式实现 */
.tank-dot {
  border-radius: 50%;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
}

.tank-dot-normal {
  background-color: rgba(82, 196, 26, 0.2);
  border: 2px solid #52c41a;
}

.tank-dot-warning {
  background-color: rgba(250, 173, 20, 0.2);
  border: 2px solid #faad14;
}

.tank-dot-alert {
  background-color: rgba(255, 77, 79, 0.2);
  border: 2px solid #ff4d4f;
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

.nav-item-active {
  background-color: rgba(22, 93, 255, 0.1);
  color: #165dff;
  border-left: 4px solid #165dff;
}

.day-tab-active {
  background-color: #165dff;
  color: white;
}

/* 滑动条样式 */
.slider {
  -webkit-appearance: none;
  appearance: none;
  height: 12px;
  background: #e5e7eb;
  border-radius: 9999px;
  outline: none;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
}
.sliderBgc {
  background-color: #505153ff;
}

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 28px;
  height: 28px;
  border-radius: 9999px;
  background: #165dff;
  border: 3px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  cursor: pointer;
  transition: transform 0.1s ease;
}

.slider::-webkit-slider-thumb:hover {
  transform: scale(1.1);
}

.slider::-moz-range-thumb {
  width: 28px;
  height: 28px;
  border-radius: 9999px;
  background: #165dff;
  border: 3px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  cursor: pointer;
}

@keyframes pulse {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

/* 新增选中状态样式 */
.tank-selected {
  box-shadow: 0 0 0 5px #165dff, 0 0 12px 6px rgba(22, 93, 255, 0.4);
  transform: scale(1.1);
  z-index: 10;
  transition: all 0.3s ease;
}

/* 确保选中状态在不同状态池子上都可见 */
.tank-dot-normal.tank-selected {
  background-color: rgba(82, 196, 26, 0.4);
}

.tank-dot-warning.tank-selected {
  background-color: rgba(250, 173, 20, 0.4);
}

.tank-dot-alert.tank-selected {
  background-color: rgba(255, 77, 79, 0.4);
}

/* 恢复反馈动画 */
.restore-feedback {
  animation: fadeInOut 2s ease-in-out;
}

@keyframes fadeInOut {
  0%,
  100% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
}

.restore-button-animate {
  animation: buttonPulse 0.5s ease-in-out;
}

@keyframes buttonPulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}
/* 当滑块处于最新进度时，添加轻微阴影提示“已到最大可拖动范围” */
.slider::-webkit-slider-thumb:is(:last-child) {
  box-shadow: 0 0 0 2px #ff4d4f33, 0 2px 8px rgba(255, 77, 79, 0.2);
}
</style>
